/*
 * TOP SECRET Copyright 2006-2015 Transsion.com All right reserved. This software is the confidential and proprietary
 * information of Transsion.com ("Confidential Information"). You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license agreement you entered into with Transsion.com.
 */
package com.yunji.framework_template.orm.datasource;

import com.yunji.framework_template.common.util.StringUtil;
import lombok.Setter;

/**
 * 保存当前线程数据源的key <br>
 * ClassName:HandleDataSource <br/>
 * Date: 2017年8月16日 上午9:08:20 <br/>
 * 
 * @author fenglibin
 * @version
 * @see
 */
public class HandleDataSource {

    public static final ThreadLocal<String> holder             = new ThreadLocal<String>();
    @Setter
    public static String                    defaultCountryCode = null;
    @Setter
    private static String                   countries;
    @Setter
    private static String                   onlyCountry;

    /**
     * 绑定当前线程数据源路由的key
     * 
     * @param key
     */
    public static void putDataSource(String datasource) {
        holder.set(datasource);
    }
    
    /**
     * 获取真实的国家码，或者不能取到国家码的"--"
     * @return
     */
    public static String getRealCountryCode() {
        return holder.get();
    }

    /**
     * 获取当前线程的数据源路由的key
     * 
     * @return
     */
    public static String getDataSource() {
        if (!StringUtil.isEmpty(onlyCountry)) {
            return onlyCountry;
        }
        String countryCode = holder.get();

        /**
         * 找不到国家，或者找到的国家不在支持的国家之列，都返回默认的国家
         */
        if (StringUtil.isEmpty(countryCode) || "--".equals(countryCode)) {
            return defaultCountryCode;
        }
        if (countries.indexOf(countryCode) < 0) {
            return defaultCountryCode;
        }
        return countryCode;
    }
}
